import config
import numpy as np

OUTPUT_SLOT_SIZE = 100


def smt_postprocess(tasks,start_times,freqs):
    set_machines =set()
    for task in tasks.values():
        set_machines.add(task.get('fix'))
        set_machines.update(task.get('next',[]))
        
    n_machines = len(set_machines)
    H = int(np.lcm.reduce([tasks[i]['T'] for i in range(len(tasks))]))
    
    if OUTPUT_SLOT_SIZE%H !=0:
       raise ValueError(f'{OUTPUT_SLOT_SIZE} is not divisible by {H}') 
    
    # freq transmission flag
    TX = 1
    RX = 0

    # find machine freq<-> start_time
    # mach_freq_table["machine_id"]={"start_time:(freq_id_tx/rx,transaction_id)"}
    mach_freq_table= {}
    for k,task in tasks.items():
        if task['fix'] not in mach_freq_table:
            mach_freq_table[task['fix']] = []
        if task['next'][0] not in mach_freq_table:
            mach_freq_table[task['next'][0]] = []
        for i,s in enumerate(start_times[k]):
            mach_freq_table[task['fix']].append((freqs[k][i],TX,s))
            mach_freq_table[task['next'][0]].append((freqs[k][i],RX,s))
    
    mach_slot_dir = {}
    for mach_idx,mach in mach_freq_table.items():
        slot_list = [0x80] * H
        for t in mach:
            freq,isTX,s = t
            s_mod = s % H
            # valid data
            if not (0 <= freq < 16):
                raise ValueError(f"频点必须在0-15范围内，当前为{freq}")
            if isTX not in (0, 1):
                raise ValueError(f"方向必须是0或1，当前为{isTX}")

            byte_val = (isTX<<4)|freq
            slot_list[s_mod] = byte_val
        # repeat schedule list   
        slot_list = slot_list * (OUTPUT_SLOT_SIZE//H)
        mach_slot_dir[mach_idx] = slot_list
        
        print(mach_idx,mach_slot_dir[mach_idx])
        
    return mach_slot_dir



        
        
